package tech.yunland.shop.domain.handler;

import com.moyuer.bsf.domain.model.Organ;
import com.moyuer.bsf.domain.model.User;
import com.moyuer.bsf.domain.service.OrganService;
import com.moyuer.bsf.domain.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import tech.yunland.shop.domain.model.SaleBill;
import tech.yunland.shop.domain.model.SaleBillEntry;
import tech.yunland.shop.domain.service.SaleBillService;
import tech.yunland.shop.domain.service.WeiXinServices;
import tech.yunland.weixin.domain.model.OrganWexin;
import tech.yunland.weixin.domain.service.OrganWexinService;
import tech.yunland.weixin.handler.MessageHandler;
import tech.yunland.weixin.protocol.BaseArticle;
import tech.yunland.weixin.protocol.BaseMessage;
import tech.yunland.weixin.protocol.message.TextMessage;
import tech.yunland.weixin.protocol.send.reply.NewsReplyMsg;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 会员消费记录
 * 实现微信模块中的MessageHandler 便可处理相应的消息
 * 这里处理的是消费记录查询
 * @author 李珂<likenamehaojie@hotmail.com>
 */

@Component
public class ExpenseMessageHandler implements MessageHandler<BaseMessage> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${weixin.api.host_url}")
    private String host;
    @Autowired
    private UserService userService;

    @Autowired
    private WeiXinServices weiXinServices;
    @Autowired
    private OrganService organService;

    @Autowired
    private SaleBillService saleBillService;
    @Autowired
    private OrganWexinService organWexinService;
    @Override
    public BaseMessage deal(BaseMessage inputMessage) {
        logger.info(this.getClass().getName(),"正在处理查询优惠活动事件");
       if(this.getExpense(inputMessage).equals("请先绑定")){
           NewsReplyMsg result = new NewsReplyMsg();
           result.setFromUser(inputMessage.getToUser());
           result.setToUser(inputMessage.getFromUser());
           result.setCreateTime(new Date());
           result.setType(BaseMessage.MsgType.news);
           List<BaseArticle> articleList = new ArrayList<BaseArticle>();
           BaseArticle article = new BaseArticle();
           article.setTitle("请先绑定会员卡");
           article.setDescription("未绑定会员卡不可进行查询操作");
           article.setPicUrl("http://api.yunlandtech.com/uploads/52dd658e-7e54-4ac8-ada5-ee6524550a7f.jpg");
           OrganWexin organWexin = organWexinService.getBywxNumber(inputMessage.getToUser());
           Organ organ = organWexin.getOwner();
           String organId = organ.getId();
           article.setUrl(host + "/#/bind/"+inputMessage.getToUser()+"/"+inputMessage.getFromUser()+"?organId="+organId);
           articleList.add(article);
           result.setArticles(articleList);
           result.setArticleCount(articleList.size());
           return result;

       }else {
           TextMessage result = new TextMessage();
           result.setFromUser(inputMessage.getToUser());
           result.setToUser(inputMessage.getFromUser());
           result.setContent(this.getExpense(inputMessage));
           result.setCreateTime(new Date());
           result.setType(BaseMessage.MsgType.text);

           return result;
       }
    }

    public String getExpense(BaseMessage inputMessage) {

        StringBuffer buffer = new StringBuffer();

        User user = userService.get(inputMessage.getToUser(), inputMessage.getFromUser());
        if (user == null) {
           // throw new RuntimeException("请先绑定");
            return "请先绑定";
        }

 /*       String organId = weiXinServices.getByOpenId(inputMessage.getFromUser());
        Organ organ = organService.get(organId);*/
        OrganWexin organWexin = organWexinService.getBywxNumber(inputMessage.getToUser());
        Organ organ = organWexin.getOwner();
        List<SaleBill> saleBills = saleBillService.getAllEntryInfo(user,organ, 1, 0, 10);
        if (saleBills == null || saleBills.size() == 0) {
            buffer.append("暂无");
            return buffer.toString();
        }

        buffer.append("尊敬的" + user.getName() + ", ");
        buffer.append("以下是您最近的消费记录: ").append(System.lineSeparator());
        buffer.append("--------------------").append(System.lineSeparator());

        for (int i = 0; i < saleBills.size(); i++) {
            SaleBill saleBill = saleBills.get(i);
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            buffer.append(format.format(saleBill.getCreateTime())).append("\n");
            for (SaleBillEntry entry : saleBill.getEntries()) {
                String goodsId = entry.getGoodsId();
                buffer.append(entry.getGoodsName() + "  " + entry.getQuantity().intValue() + saleBillService.getGoodsUnit(goodsId).getUnit() + "  " + entry.getGoodsPrice()).append("元\n");
            }
            buffer.append("实收金额: " + saleBill.getReceived()).append("元\n");
            buffer.append("--------------------").append(System.lineSeparator());
        }
        buffer.append("如有疑问, 请到店咨询。");

        return buffer.toString();
    }

}

